package api

import (
	"TaskAssignmentSystem/internal/admin/dao"
	"TaskAssignmentSystem/internal/admin/services"
	"TaskAssignmentSystem/internal/pkg/middleware/handler"
	"TaskAssignmentSystem/pkg/oss"
	"TaskAssignmentSystem/pkg/utils"
	"errors"
	"fmt"
	"github.com/go-the-way/exl"
	"github.com/kataras/iris/v12"
	"io/ioutil"
	"os"
	"strings"
	"time"
)

type ProhibitedWordsListRequest struct {
	ProhibitedWord string `json:"prohibited_word"`
	StartTime      string `json:"start_time"`
	EndTime        string `json:"end_time"`
	Page           int64  `json:"page" validate:"required"`
	PageSize       int64  `json:"page_size" validate:"required"`
}

func ProhibitedWordsListHandler(ctx iris.Context) {
	var RequestParams ProhibitedWordsListRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var systemProhibitedWordsServe services.SystemProhibitedWordsService
	if total, list, err := systemProhibitedWordsServe.QueryProhibitedWordsPage(RequestParams.ProhibitedWord, RequestParams.StartTime, RequestParams.EndTime, RequestParams.Page, RequestParams.PageSize); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(iris.Map{"count": total, "list": list}))
		return
	}
}

type ProhibitedWordsBatchDelRequest struct {
	//Ids []string `json:"ids" validate:"required"`
	GroupNo []string `json:"group_no" validate:"required"`
}

func ProhibitedWordsBatchDelHandler(ctx iris.Context) {
	var RequestParams ProhibitedWordsBatchDelRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var systemProhibitedWordsServe services.SystemProhibitedWordsService
	if err := systemProhibitedWordsServe.ProhibitedWordsBatchDel(RequestParams.GroupNo); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type ImportProhibitedWords struct {
	GroupNo        int    `excel:"组序号"`
	GroupTag       string `excel:"组标签"`
	ProhibitedWord string `excel:"单词（可以使用逗号间隔开）"`
}

func (*ImportProhibitedWords) Configure(rc *exl.ReadConfig) {}
func BatchImportProhibitedWordsHandler(ctx iris.Context) {
	_, handle, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, _ := handle.Open()
	defer file.Close()
	if models, err := exl.Read[*ImportProhibitedWords](file); err != nil {
		fmt.Println("read excel err:" + err.Error())
		ctx.JSON(utils.ResponseServerError(errors.New("excel读取错误")))
		return
	} else {
		fmt.Printf("read excel num: %d\n", len(models))
		var prohibitedWordsObjs []*dao.SystemProhibitedWords
		index := 0
		idx := 0
		for i, model := range models {
			//从第二行开始读取
			if i == 0 {
				continue
			}
			prohibitedWord := strings.ReplaceAll(model.ProhibitedWord, "，", ",")
			prohibitedWords := strings.Split(prohibitedWord, ",")
			//按,分隔每个词,然后导入
			for _, word := range prohibitedWords {
				var prohibitedWordsObj dao.SystemProhibitedWords
				prohibitedWordsObj.GroupNo = model.GroupNo
				prohibitedWordsObj.GroupTag = model.GroupTag
				prohibitedWordsObj.ProhibitedWord = word
				prohibitedWordsObjs = append(prohibitedWordsObjs, &prohibitedWordsObj)
				idx++
			}
			index++
		}
		var systemProhibitedWordsServe services.SystemProhibitedWordsService
		if err := systemProhibitedWordsServe.BatchImportProhibitedWords(prohibitedWordsObjs); err != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		}
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type DelProhibitedWords struct {
	ProhibitedWord string `excel:"单词（可以使用逗号间隔开）"`
}

func (*DelProhibitedWords) Configure(rc *exl.ReadConfig) {}
func BatchDelProhibitedWordsHandler(ctx iris.Context) {
	_, handle, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, _ := handle.Open()
	defer file.Close()
	if models, err := exl.Read[*ImportProhibitedWords](file); err != nil {
		fmt.Println("read excel err:" + err.Error())
		ctx.JSON(utils.ResponseServerError(errors.New("excel读取错误")))
		return
	} else {
		fmt.Printf("read excel num: %d\n", len(models))
		var prohibitedWordsObjs []*dao.SystemProhibitedWords
		index := 0
		idx := 0
		for i, model := range models {
			//从第二行开始读取
			if i == 0 {
				continue
			}
			prohibitedWord := strings.ReplaceAll(model.ProhibitedWord, "，", ",")
			prohibitedWords := strings.Split(prohibitedWord, ",")
			//按,分隔每个词,然后导入
			for _, word := range prohibitedWords {
				var prohibitedWordsObj dao.SystemProhibitedWords
				prohibitedWordsObj.ProhibitedWord = word
				prohibitedWordsObjs = append(prohibitedWordsObjs, &prohibitedWordsObj)
				idx++
			}
			index++
		}
		var systemProhibitedWordsServe services.SystemProhibitedWordsService
		if err := systemProhibitedWordsServe.BatchDelProhibitedWords(prohibitedWordsObjs); err != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		}
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type ExportProhibitedWords struct {
	GroupNo        int    `excel:"组序号"`
	GroupTag       string `excel:"组标签"`
	ProhibitedWord string `excel:"单词（可以使用逗号间隔开）"`
}

type ExportProhibitedWordsRequest struct {
	GroupNos []string `json:"group_nos"`
}

func (*ExportProhibitedWords) Configure(rc *exl.WriteConfig) {}
func BatchExportProhibitedWordsHandler(ctx iris.Context) {
	var RequestParams ExportProhibitedWordsRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var serve services.CommonService[dao.SystemProhibitedWords]
	if len(RequestParams.GroupNos) > 0 {
		//groupNos := strings.Split(RequestParams.GroupNos, ",")
		groupNos := strings.Join(RequestParams.GroupNos, ",")
		serve.WhereStr = append(serve.WhereStr, fmt.Sprintf("group_no in (%v)", groupNos))
	}
	field := fmt.Sprintf("group_no,MAX(group_tag) group_tag,GROUP_CONCAT(prohibited_word SEPARATOR '，') prohibited_word")
	serve.SelectField = &field
	serve.Group = "group_no"
	serve.Order = "group_no"
	serve.PageSize = -1
	ExportData, err := serve.SelectList()
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var exportProhibitedWords []*ExportProhibitedWords
	for _, model := range ExportData.Data {
		var exportProhibitedWord ExportProhibitedWords
		exportProhibitedWord.GroupNo = model.GroupNo
		exportProhibitedWord.GroupTag = model.GroupTag
		exportProhibitedWord.ProhibitedWord = model.ProhibitedWord
		exportProhibitedWords = append(exportProhibitedWords, &exportProhibitedWord)
	}

	unix := time.Now().UnixNano()
	if err := exl.Write(fmt.Sprintf("./export/export_prohibited_words_records_%d.xlsx", unix), exportProhibitedWords); err != nil {
		fmt.Println("write excel err:" + err.Error())
		return
	}
	tempFilename := fmt.Sprintf("./export/export_prohibited_words_records_%d.xlsx", unix)
	//删除本地临时文件
	defer os.Remove(tempFilename)
	bucketClient := oss.BucketClient{}
	readFile, _ := ioutil.ReadFile(fmt.Sprintf("./export/export_prohibited_words_records_%d.xlsx", unix))
	bucketClient.UpBytes(readFile, fmt.Sprintf("task-assign/export/export_prohibited_words_records_%d.xlsx", unix))
	ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: fmt.Sprintf("%s/task-assign/export/export_prohibited_words_records_%d.xlsx", utils.ServerConf.AliOssConf.CallBackHost, unix)})
	return
}

func AlterUserNickNameAndIntroductionHandler(ctx iris.Context) {
	var systemProhibitedWordsServe services.SystemProhibitedWordsService
	if err := systemProhibitedWordsServe.AlterUserNickNameAndIntroduction(); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	}
	ctx.JSON(utils.ResponseOK())
	return

}
